package p

import (
	"gitee.com/tietang/terrace-go/v2/base"
	"github.com/influxdata/influxdb-client-go/api"
	"github.com/silenceper/pool"
	log "github.com/sirupsen/logrus"
	"github.com/tietang/props/v3/kvs"
	"time"
)

var poolWriteAPI *WriteAPIPool
var poolQueryAPI *QueryAPIPool
var poolWriteAPIBlocking *WriteAPIBlockingPool

func PoolWriteAPI() *WriteAPIPool {
	base.Check(poolWriteAPI)
	return poolWriteAPI
}
func ExeWrite(fn func(api api.WriteAPI) error) {
	PoolWriteAPI().Exe(fn)
}
func ExeWriteB(fn func(api api.WriteAPIBlocking) error) {
	PoolWriteAPIBlocking().Exe(fn)
}
func ExeQuery(fn func(api api.QueryAPI) error) {
	PoolQueryAPI().Exe(fn)
}
func PoolWriteAPIBlocking() *WriteAPIBlockingPool {
	base.Check(poolWriteAPIBlocking)
	return poolWriteAPIBlocking
}

func PoolQueryAPI() *QueryAPIPool {
	base.Check(poolQueryAPI)
	return poolQueryAPI
}

type InfluxPoolStarter struct {
	base.BaseStarter
	poolConfig           pool.Config
	PoolWriteAPI         *WriteAPIPool
	PoolQueryAPI         *QueryAPIPool
	PoolWriteAPIBlocking *WriteAPIBlockingPool
}

func (s *InfluxPoolStarter) Init(ctx base.StarterContext) {
	conf := ctx.Props()
	s.poolConfig = pool.Config{
		InitialCap: 5,  //资源池初始连接数
		MaxIdle:    20, //最大空闲连接数
		MaxCap:     30, //最大并发连接数
		//Ping:       ping,
		//连接最大空闲时间，超过该时间的连接 将会关闭，可避免空闲时连接EOF，自动失效的问题
		IdleTimeout: 15 * time.Minute,
	}
	err := kvs.Unmarshal(conf, &s.poolConfig, "influxDb.pool")
	if err != nil {
		log.Error(err)
	}
	log.Infof("influxDb options: %+v\n", s.poolConfig)

	////创建一个连接池： 初始化5，最大空闲连接是20，最大并发连接30
	//s.poolConfig = &pool.Config{
	//	InitialCap: 5,  //资源池初始连接数
	//	MaxIdle:    20, //最大空闲连接数
	//	MaxCap:     30, //最大并发连接数
	//	//Ping:       ping,
	//	//连接最大空闲时间，超过该时间的连接 将会关闭，可避免空闲时连接EOF，自动失效的问题
	//	IdleTimeout: 15 * time.Second,
	//}
}
func (s *InfluxPoolStarter) Start(ctx base.StarterContext) {
	s.PoolWriteAPI = NewPoolWriteAPI(s.poolConfig)
	s.PoolQueryAPI = NewPoolQueryAPI(s.poolConfig)
	s.PoolWriteAPIBlocking = NewPoolWriteAPIBlocking(s.poolConfig)
	poolWriteAPI = s.PoolWriteAPI
	poolQueryAPI = s.PoolQueryAPI
	poolWriteAPIBlocking = s.PoolWriteAPIBlocking
}

func (s *InfluxPoolStarter) Stop(ctx base.StarterContext) {

}
